/**
 * 医疗设备数据操作API
 * 用于管理医院的医疗设备和设施
 */

import { hospitalDB, MedicalEquipmentData } from '../indexedDB'

export interface CreateMedicalEquipmentRequest {
  hospitalId: string
  departmentId?: string
  floorId?: string
  name: string
  type: 'ct' | 'mri' | 'xray' | 'ultrasound' | 'bed' | 'wheelchair' | 'defibrillator' | 'ventilator' | 'toilet' | 'elevator' | 'entrance' | 'exit'
  position: [number, number]
  description?: string
  specifications?: string
  manufacturer?: string
  status?: 'active' | 'inactive' | 'maintenance' | 'reserved'
  metadata?: Record<string, any>
}

export interface UpdateMedicalEquipmentRequest extends Partial<CreateMedicalEquipmentRequest> {
  id: string
}

export interface MedicalEquipmentResponse {
  success: boolean
  msg: string
  data?: MedicalEquipmentData
}

export interface MedicalEquipmentListResponse {
  success: boolean
  msg: string
  data?: MedicalEquipmentData[]
}

/**
 * 创建医疗设备
 */
export const createMedicalEquipment = async (
  equipment: CreateMedicalEquipmentRequest
): Promise<MedicalEquipmentResponse> => {
  try {
    const data = await hospitalDB.addMedicalEquipment({
      ...equipment,
      status: equipment.status || 'active',
      metadata: equipment.metadata || {}
    })
    
    return {
      success: true,
      msg: '医疗设备创建成功',
      data
    }
  } catch (error) {
    console.error('创建医疗设备失败:', error)
    return {
      success: false,
      msg: '创建医疗设备失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据医院ID获取设备列表
 */
export const getMedicalEquipmentByHospital = async (
  hospitalId: string
): Promise<MedicalEquipmentListResponse> => {
  try {
    const data = await hospitalDB.getMedicalEquipmentByHospital(hospitalId)
    return {
      success: true,
      msg: '获取医疗设备列表成功',
      data
    }
  } catch (error) {
    console.error('获取医疗设备列表失败:', error)
    return {
      success: false,
      msg: '获取医疗设备列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据科室ID获取设备列表
 */
export const getMedicalEquipmentByDepartment = async (
  departmentId: string
): Promise<MedicalEquipmentListResponse> => {
  try {
    const data = await hospitalDB.getMedicalEquipmentByDepartment(departmentId)
    return {
      success: true,
      msg: '获取科室设备列表成功',
      data
    }
  } catch (error) {
    console.error('获取科室设备列表失败:', error)
    return {
      success: false,
      msg: '获取科室设备列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据楼层ID获取设备列表
 */
export const getMedicalEquipmentByFloor = async (
  floorId: string
): Promise<MedicalEquipmentListResponse> => {
  try {
    const data = await hospitalDB.getMedicalEquipmentByFloor(floorId)
    return {
      success: true,
      msg: '获取楼层设备列表成功',
      data
    }
  } catch (error) {
    console.error('获取楼层设备列表失败:', error)
    return {
      success: false,
      msg: '获取楼层设备列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 更新医疗设备信息
 */
export const updateMedicalEquipment = async (
  id: string,
  updates: Partial<CreateMedicalEquipmentRequest>
): Promise<MedicalEquipmentResponse> => {
  try {
    // 先获取现有数据
    const existing = await hospitalDB.getMedicalEquipment(id)
    if (!existing) {
      return {
        success: false,
        msg: '医疗设备不存在'
      }
    }
    
    // 合并更新数据
    const updatedData: MedicalEquipmentData = {
      ...existing,
      ...updates,
      id,
      updatedAt: new Date()
    }
    
    await hospitalDB.updateMedicalEquipment(updatedData)
    
    return {
      success: true,
      msg: '医疗设备更新成功',
      data: updatedData
    }
  } catch (error) {
    console.error('更新医疗设备失败:', error)
    return {
      success: false,
      msg: '更新医疗设备失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 删除医疗设备
 */
export const deleteMedicalEquipment = async (id: string): Promise<MedicalEquipmentResponse> => {
  try {
    await hospitalDB.deleteMedicalEquipment(id)
    return {
      success: true,
      msg: '医疗设备删除成功'
    }
  } catch (error) {
    console.error('删除医疗设备失败:', error)
    return {
      success: false,
      msg: '删除医疗设备失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 医疗设备类型配置
 */
export const getMedicalEquipmentTypes = () => {
  return [
    { 
      type: 'ct', 
      label: 'CT扫描仪', 
      icon: '🏥', 
      color: '#3b82f6',
      description: '计算机断层扫描设备',
      category: 'imaging'
    },
    { 
      type: 'mri', 
      label: 'MRI核磁共振', 
      icon: '🧲', 
      color: '#8b5cf6',
      description: '磁共振成像设备',
      category: 'imaging'
    },
    { 
      type: 'xray', 
      label: 'X光机', 
      icon: '☢️', 
      color: '#f59e0b',
      description: 'X射线摄影设备',
      category: 'imaging'
    },
    { 
      type: 'ultrasound', 
      label: 'B超设备', 
      icon: '📡', 
      color: '#06b6d4',
      description: '超声波检查设备',
      category: 'imaging'
    },
    { 
      type: 'bed', 
      label: '病床', 
      icon: '🛏️', 
      color: '#10b981',
      description: '患者床位',
      category: 'furniture'
    },
    { 
      type: 'wheelchair', 
      label: '轮椅', 
      icon: '♿', 
      color: '#84cc16',
      description: '患者轮椅',
      category: 'mobility'
    },
    { 
      type: 'defibrillator', 
      label: '除颤器', 
      icon: '⚡', 
      color: '#ef4444',
      description: '心脏除颤设备',
      category: 'emergency'
    },
    { 
      type: 'ventilator', 
      label: '呼吸机', 
      icon: '💨', 
      color: '#f97316',
      description: '机械通气设备',
      category: 'life_support'
    },
    { 
      type: 'toilet', 
      label: '卫生间', 
      icon: '🚻', 
      color: '#6b7280',
      description: '患者卫生间',
      category: 'facility'
    },
    { 
      type: 'elevator', 
      label: '电梯', 
      icon: '🛗', 
      color: '#64748b',
      description: '医院电梯',
      category: 'facility'
    },
    { 
      type: 'entrance', 
      label: '入口', 
      icon: '🚪', 
      color: '#059669',
      description: '医院入口',
      category: 'facility'
    },
    { 
      type: 'exit', 
      label: '出口', 
      icon: '🚶', 
      color: '#dc2626',
      description: '紧急出口',
      category: 'facility'
    }
  ]
}

/**
 * 设备状态选项
 */
export const getMedicalEquipmentStatusOptions = () => {
  return [
    { label: '正常使用', value: 'active', color: '#10b981' },
    { label: '停用', value: 'inactive', color: '#6b7280' },
    { label: '维护中', value: 'maintenance', color: '#f59e0b' },
    { label: '已预约', value: 'reserved', color: '#3b82f6' }
  ]
}

/**
 * 按类别分组设备类型
 */
export const getEquipmentTypesByCategory = () => {
  const types = getMedicalEquipmentTypes()
  const categories = {
    imaging: { label: '影像设备', types: [] as any[] },
    emergency: { label: '急救设备', types: [] as any[] },
    life_support: { label: '生命支持', types: [] as any[] },
    furniture: { label: '医用家具', types: [] as any[] },
    mobility: { label: '移动辅具', types: [] as any[] },
    facility: { label: '基础设施', types: [] as any[] }
  }
  
  types.forEach(type => {
    const category = type.category as keyof typeof categories
    if (categories[category]) {
      categories[category].types.push(type)
    }
  })
  
  return categories
}